const express = require("express");
const router = express.Router();
const db = require("../config/database");
const { body, validationResult } = require("express-validator");
const {
  authenticateToken,
  generateString,
  encryptPhone,
  decryptPhone,
  extractNumber,
  getNextId,
  logUserOperation,
} = require("../untils/untils");
const dayjs = require("dayjs");
const { cryptoHelper } = require("../config/global");
const openAI = require("../utils/openAI");

// 获取跟进记录
// 参数 :     cust_id: '', follow_date: '', emp_id: '', method: '',
router.get("/", authenticateToken, async (req, res) => {
  try {
    const { cust_id, follow_date, emp_id, method } = req.query;

    let sql = `SELECT * FROM follow_record WHERE 1 = 1`;
    if (cust_id) {
      sql += ` AND cust_id = '${cust_id}'`;
    }

    if (follow_date) {
      sql += ` AND follow_date = '${follow_date}'`;
    }

    if (emp_id) {
      sql += ` AND emp_id = '${emp_id}'`;
    }

    if (method) {
      sql += ` AND method = '${method}'`;
    }

    const [result] = await db.execute(sql);

    // 翻译客户名称
    const [cust_info] = await db.execute(`SELECT * FROM customer`);
    result.forEach((item) => {
      item.cust_name =
        cust_info.find((cust) => cust.cust_id === item.cust_id)?.cust_name ||
        item.cust_id;
    });

    // 翻译跟进人员名称
    const [emp_info] = await db.execute(`SELECT * FROM employee`);
    result.forEach((item) => {
      item.emp_name =
        emp_info.find((emp) => emp.emp_id === item.emp_id)?.emp_name ||
        item.emp_id;
    });

    result.forEach((item) => {
      item.follow_date = item.follow_date
        ? dayjs(item.follow_date).format("YYYY-MM-DD")
        : "";
      item.next_date = item.next_date
        ? dayjs(item.next_date).format("YYYY-MM-DD")
        : "";
    });

    await logUserOperation(
      req,
      "查询",
      "获取跟进记录",
      "获取跟进记录成功",
      "成功"
    );

    res.json({
      success: true,
      data: result,
    });
  } catch (error) {
    console.error("获取跟进记录失败:", error);
    await logUserOperation(
      req,
      "查询",
      "获取跟进记录",
      "获取跟进记录失败",
      "失败",
      error.message
    );
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
    });
  }
});

// 添加跟进记录
router.put("/add", authenticateToken, async (req, res) => {
  try {
    let {
      cust_id,
      follow_date,
      emp_id,
      method,
      result,
      next_date,
      next_plan,
      suggestion,
    } = req.body;
    const follow_id = await getNextId("F", "follow_id", "follow_record", 5);
    // 生成跟进建议 并记录到数据库
    // openAI.business_opportunity_record(result, follow_id);

    if (!next_date) {
      next_date = null;
    } else {
      next_date = dayjs(next_date).format("YYYY-MM-DD HH:mm:ss");
    }

    const sql = `INSERT INTO follow_record (follow_id, cust_id, follow_date, emp_id, method, result, next_date, next_plan,suggestion) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
    const [follow_record_result] = await db.execute(sql, [
      follow_id,
      cust_id,
      follow_date,
      emp_id,
      method,
      result,
      next_date,
      next_plan,
      suggestion,
    ]);
    await logUserOperation(
      req,
      "添加",
      "新增跟进记录",
      "新增跟进记录成功",
      "成功"
    );
    res.json({
      success: true,
      data: follow_record_result,
    });
  } catch (error) {
    console.error("添加跟进记录失败:", error);
    await logUserOperation(
      req,
      "添加",
      "新增跟进记录",
      "新增跟进记录失败",
      "失败",
      error.message
    );
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
    });
  }
});


// {"cust_id":"C00001","follow_date":"2025-10-07","emp_id":"MG00002","method":"电话沟通","result":"非常满意\n","suggestion":"根据本次跟进结果‘非常满意’，客户对产品或服务表现出高度认可，建议在3-5天内进行下一次跟进，重点围绕深化合作关系展开：1. 发送个性化感谢邮件，重申客户满意点并附上相关成功案例或增值资料（如行业白皮书），以强化信任；2. 主动预约一次简短通话或会议，探讨客户后续需求（如升级服务、附加功能或推荐其他部门使用），同时询问是否有推荐机会；3. 记录客户关键偏好，为后续定制化方案做准备。此举旨在利用满意情绪加速决策，防止竞争介入，并挖掘潜在增购机会。","next_date":"2025-10-20","next_plan":"","follow_id":"F00003"}
// 编辑跟进记录
router.post("/update", authenticateToken, async (req, res) => {
  try {
    let {
      follow_id,
      cust_id,
      follow_date,
      emp_id,
      method,
      result,
      next_date,
      next_plan,
      suggestion,
    } = req.body;

    

    const sql = `UPDATE follow_record SET cust_id = ?, follow_date = ?, emp_id = ?, method = ?, result = ?, next_date = ?, next_plan = ?,suggestion = ? WHERE follow_id = ?`;

    if (!next_date) {
      next_date = null;
    }

    const [follow_record_result] = await db.execute(sql, [
      cust_id,
      follow_date,
      emp_id,
      method,
      result,
      next_date,
      next_plan,
      suggestion,
      follow_id,
    ]);

    await logUserOperation(
      req,
      "更新",
      "更新跟进记录",
      "更新跟进记录成功",
      "成功"
    );

    res.json({
      success: true,
      data: follow_record_result,
    });
  } catch (error) {
    console.error("编辑跟进记录失败:", error);
    await logUserOperation(
      req,
      "更新",
      "更新跟进记录",
      "更新跟进记录失败",
      "失败",
      error.message
    );
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
    });
  }
});

// 删除跟进记录
router.delete("/delete", authenticateToken, async (req, res) => {
  try {
    const { follow_id } = req.query;
    const sql = `DELETE FROM follow_record WHERE follow_id = ?`;
    const [follow_record_result] = await db.execute(sql, [follow_id]);
    await logUserOperation(
      req,
      "删除",
      "删除跟进记录",
      "删除跟进记录成功",
      "成功"
    );
    res.json({
      success: true,
      data: follow_record_result,
    });
  } catch (error) {
    console.error("删除跟进记录失败:", error);
    await logUserOperation(
      req,
      "删除",
      "删除跟进记录",
      "删除跟进记录失败",
      "失败",
      error.message
    );
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
    });
  }
});

// 获取跟进方式
router.get("/follow_way", authenticateToken, async (req, res) => {
  let follow_way = [
    {
      key: "电话沟通",
      name: "电话沟通",
    },
    {
      key: "微信沟通",
      name: "微信沟通",
    },
    {
      key: "现场拜访",
      name: "现场拜访",
    },
  ];
  res.json({
    success: true,
    data: follow_way,
  });
});

// 获取查询项客户
router.get("/cust", authenticateToken, async (req, res) => {
  try {
    const [result] = await db.execute(
      `SELECT DISTINCT customer.cust_id , customer.cust_name FROM customer JOIN follow_record ON customer.cust_id = follow_record.cust_id`
    );
    res.json({
      success: true,
      data: result,
    });
  } catch (error) {
    console.error("获取查询项客户失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
    });
  }
});

// 获取查询项跟进人员
router.get("/emp", authenticateToken, async (req, res) => {
  try {
    const [result] = await db.execute(
      `SELECT DISTINCT employee.emp_id , employee.emp_name FROM employee JOIN follow_record ON employee.emp_id = follow_record.emp_id`
    );
    res.json({
      success: true,
      data: result,
    });
  } catch (error) {
    console.error("获取查询项跟进人员失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
    });
  }
});

// 获取查询项跟进方式
router.get("/method", authenticateToken, async (req, res) => {
  try {
    const [result] = await db.execute(
      `SELECT DISTINCT method as 'key', method as 'name' FROM follow_record`
    );
    res.json({
      success: true,
      data: result,
    });
  } catch (error) {
    console.error("获取查询项跟进方式失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
    });
  }
});

// AI生成跟进建议
router.post("/suggestion", authenticateToken, async (req, res) => {
  try {
    const { oppo_id, demand_desc } = req.body;
    console.log("oppo_id, demand_desc:", oppo_id, demand_desc);

    const suggestion = await openAI.business_opportunity_record(demand_desc);
    const newsugestion = JSON.parse(suggestion);
    res.json({
      success: true,
      data: newsugestion.suggestion,
    });
  } catch (error) {
    console.error("AI 生成商机需求总结失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
    });
  }
});

module.exports = router;
